import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as templateApi from '@/api/template'

export const useTemplateStore = defineStore('template', () => {
  // 状态
  const templates = ref([])
  const currentTemplate = ref(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取模板列表
  const fetchTemplates = async (params) => {
    loading.value = true
    try {
      const data = await templateApi.getTemplateList(params)
      templates.value = data.items || []
      total.value = data.total || 0
      return data
    } finally {
      loading.value = false
    }
  }

  // 获取模板详情
  const fetchTemplateDetail = async (id) => {
    loading.value = true
    try {
      const data = await templateApi.getTemplateDetail(id)
      currentTemplate.value = data
      return data
    } finally {
      loading.value = false
    }
  }

  // 创建模板
  const createTemplate = async (data) => {
    return await templateApi.createTemplate(data)
  }

  // 更新模板
  const updateTemplate = async (id, data) => {
    return await templateApi.updateTemplate(id, data)
  }

  // 删除模板
  const deleteTemplate = async (id) => {
    return await templateApi.deleteTemplate(id)
  }

  // 版本回滚
  const rollbackVersion = async (id, version) => {
    return await templateApi.rollbackVersion(id, version)
  }

  // 获取版本对比
  const getVersionDiff = async (id, params) => {
    return await templateApi.getVersionDiff(id, params)
  }

  // 重置当前模板
  const resetCurrentTemplate = () => {
    currentTemplate.value = null
  }

  // 别名方法：getTemplateById 等同于 fetchTemplateDetail
  const getTemplateById = fetchTemplateDetail

  return {
    templates,
    currentTemplate,
    loading,
    total,
    fetchTemplates,
    fetchTemplateDetail,
    getTemplateById,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    rollbackVersion,
    getVersionDiff,
    resetCurrentTemplate
  }
})
